// 表单验证工具

/**
 * 验证规则接口
 */
export interface ValidationRule {
  required?: boolean
  pattern?: RegExp
  minLength?: number
  maxLength?: number
  message: string
}

/**
 * 验证结果接口
 */
export interface ValidationResult {
  isValid: boolean
  message?: string
}

/**
 * 表单验证工具类
 */
export class ValidationUtils {
  
  /**
   * 邮箱验证
   */
  static validateEmail(email: string): ValidationResult {
    if (!email) {
      return { isValid: false, message: '请输入邮箱' }
    }
    
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!emailRegex.test(email)) {
      return { isValid: false, message: '请输入正确的邮箱格式' }
    }
    
    return { isValid: true }
  }
  
  /**
   * 密码验证
   */
  static validatePassword(password: string, options?: {
    minLength?: number
    requireSpecialChar?: boolean
    requireNumber?: boolean
    requireUpperCase?: boolean
  }): ValidationResult {
    const {
      minLength = 6,
      requireSpecialChar = false,
      requireNumber = false,
      requireUpperCase = false
    } = options || {}
    
    if (!password) {
      return { isValid: false, message: '请输入密码' }
    }
    
    if (password.length < minLength) {
      return { isValid: false, message: `密码长度不能少于${minLength}位` }
    }
    
    if (requireNumber && !/\d/.test(password)) {
      return { isValid: false, message: '密码必须包含数字' }
    }
    
    if (requireUpperCase && !/[A-Z]/.test(password)) {
      return { isValid: false, message: '密码必须包含大写字母' }
    }
    
    if (requireSpecialChar && !/[!@#$%^&*(),.?":{}|<>]/.test(password)) {
      return { isValid: false, message: '密码必须包含特殊字符' }
    }
    
    return { isValid: true }
  }
  
  /**
   * 确认密码验证
   */
  static validateConfirmPassword(password: string, confirmPassword: string): ValidationResult {
    if (!confirmPassword) {
      return { isValid: false, message: '请确认密码' }
    }
    
    if (password !== confirmPassword) {
      return { isValid: false, message: '两次输入的密码不一致' }
    }
    
    return { isValid: true }
  }
  
  /**
   * 手机号验证
   */
  static validatePhone(phone: string): ValidationResult {
    if (!phone) {
      return { isValid: false, message: '请输入手机号' }
    }
    
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phoneRegex.test(phone)) {
      return { isValid: false, message: '请输入正确的手机号格式' }
    }
    
    return { isValid: true }
  }
  
  /**
   * 昵称验证
   */
  static validateNickname(nickname: string): ValidationResult {
    if (!nickname) {
      return { isValid: false, message: '请输入昵称' }
    }
    
    if (nickname.length < 2) {
      return { isValid: false, message: '昵称长度不能少于2位' }
    }
    
    if (nickname.length > 20) {
      return { isValid: false, message: '昵称长度不能超过20位' }
    }
    
    // 检查是否包含特殊字符（只允许中文、英文、数字、下划线）
    const nicknameRegex = /^[\u4e00-\u9fa5a-zA-Z0-9_]+$/
    if (!nicknameRegex.test(nickname)) {
      return { isValid: false, message: '昵称只能包含中文、英文、数字和下划线' }
    }
    
    return { isValid: true }
  }
  
  /**
   * 验证码验证
   */
  static validateVerificationCode(code: string, length: number = 6): ValidationResult {
    if (!code) {
      return { isValid: false, message: '请输入验证码' }
    }
    
    if (code.length !== length) {
      return { isValid: false, message: `验证码应为${length}位` }
    }
    
    const codeRegex = /^\d+$/
    if (!codeRegex.test(code)) {
      return { isValid: false, message: '验证码只能包含数字' }
    }
    
    return { isValid: true }
  }
  
  /**
   * 通用字段验证
   */
  static validateField(value: string, rules: ValidationRule[]): ValidationResult {
    for (const rule of rules) {
      // 必填验证
      if (rule.required && (!value || value.trim() === '')) {
        return { isValid: false, message: rule.message }
      }
      
      // 如果值为空且不是必填，跳过其他验证
      if (!value || value.trim() === '') {
        continue
      }
      
      // 最小长度验证
      if (rule.minLength && value.length < rule.minLength) {
        return { isValid: false, message: rule.message }
      }
      
      // 最大长度验证
      if (rule.maxLength && value.length > rule.maxLength) {
        return { isValid: false, message: rule.message }
      }
      
      // 正则表达式验证
      if (rule.pattern && !rule.pattern.test(value)) {
        return { isValid: false, message: rule.message }
      }
    }
    
    return { isValid: true }
  }
  
  /**
   * 批量验证表单字段
   */
  static validateForm(formData: Record<string, any>, validationRules: Record<string, ValidationRule[]>): {
    isValid: boolean
    errors: Record<string, string>
    firstError?: string
  } {
    const errors: Record<string, string> = {}
    let firstError: string | undefined
    
    for (const [fieldName, rules] of Object.entries(validationRules)) {
      const fieldValue = formData[fieldName]
      const result = this.validateField(fieldValue, rules)
      
      if (!result.isValid && result.message) {
        errors[fieldName] = result.message
        if (!firstError) {
          firstError = result.message
        }
      }
    }
    
    return {
      isValid: Object.keys(errors).length === 0,
      errors,
      firstError
    }
  }
}

/**
 * 常用验证规则预设
 */
export const CommonValidationRules = {
  email: [
    { required: true, message: '请输入邮箱' },
    { pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: '请输入正确的邮箱格式' }
  ],
  
  password: [
    { required: true, message: '请输入密码' },
    { minLength: 6, message: '密码长度不能少于6位' }
  ],
  
  strongPassword: [
    { required: true, message: '请输入密码' },
    { minLength: 8, message: '密码长度不能少于8位' },
    { pattern: /(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/, message: '密码必须包含大小写字母和数字' }
  ],
  
  phone: [
    { required: true, message: '请输入手机号' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式' }
  ],
  
  nickname: [
    { required: true, message: '请输入昵称' },
    { minLength: 2, message: '昵称长度不能少于2位' },
    { maxLength: 20, message: '昵称长度不能超过20位' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z0-9_]+$/, message: '昵称只能包含中文、英文、数字和下划线' }
  ],
  
  verificationCode: [
    { required: true, message: '请输入验证码' },
    { pattern: /^\d{6}$/, message: '验证码应为6位数字' }
  ]
}